<?php

require_once ABSPATH . '/system/sql.php';

//WIFI探针上传数据
if(isset($_POST['m']) && isset($_POST['d'])){
    //http_response_code(200);

    fastcgi_finish_request();

    $sql_link = MySQL::getInstance();

    $res = $sql_link->prepare('SELECT sniffer_id FROM sniffer_infos WHERE sniffer_mac=:sniffer_mac');
    $res->bindParam(':sniffer_mac',$sniffer_mac);
    $mac_temp = str_split($_POST['m'],2);
    $sniffer_mac = $mac_temp[0].':'.$mac_temp[1].':'.$mac_temp[2].':'.$mac_temp[3].':'.$mac_temp[4].':'.$mac_temp[5];
    $res->execute();
    $data = $res->fetch(PDO::FETCH_ASSOC);

    if(!empty($data)) {
        $sniffer_id = $data['sniffer_id'];

        $datas = str_split($_POST['d'],14);

        $res = $sql_link->prepare('INSERT INTO sniffer_data ( sniffer_id, user_mac, rssi) VALUES (:sniffer_id, :user_mac, :rssi)');
        $res->bindParam(':sniffer_id',$sniffer_id);
        $res->bindParam(':user_mac',$user_mac);
        $res->bindParam(':rssi',$rssi);
        foreach($datas as $data){
            $mac_temp = str_split(substr($data,0,12),2);
            $user_mac = $mac_temp[0].':'.$mac_temp[1].':'.$mac_temp[2].':'.$mac_temp[3].':'.$mac_temp[4].':'.$mac_temp[5];
            $rssi = substr($data,12,2);
            $rssi = hexdec($rssi) -256;
            $res->execute();
        }


    }else{
        require_once __DIR__.'/403.php';
    }
}else{
    require_once __DIR__.'/403.php';
}

$file = "/tmp/dou_sniffer";
if(!file_exists($file))
{
    $cmd = 'php '.ABSPATH.'system/data_handler.php >/dev/null &';
    exec($cmd);
    echo '运行数据处理脚本成功';
}else{
    echo '数据处理脚本已在运行';
}